from re import I
from flask import Blueprint, request, jsonify
from app.err_no import errno_no
import json
from loguru import logger
from app.db.mongoClient import MongoError
from app.settings.base import export_permission
import traceback
from app.db import dbUserRolePower

blueprint = Blueprint('user_rolePower', __name__, url_prefix='/api/user')

@blueprint.route('/v1/allPower_query', methods=['POST'])
def allPower_query():
    '''
    查询所有权限
    '''
    try:
        return jsonify(errno_no.OK.data(export_permission))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/rolePower_query', methods=['POST'])
def rolePower_query():
    '''
    查询指定角色的权限
    '''
    try:
        j_data = json.loads(request.data)
        roleId = j_data.get('roleId')
        if roleId is None or len(roleId) <= 0:
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbUserRolePower.rolePowerQuery(roleId)
        if res is False:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

        return jsonify(errno_no.OK.data(res))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/rolePower_edit', methods=['POST'])
def rolePower_edit():
    '''
    编辑指定角色的权限
    '''
    try:
        j_data = json.loads(request.data)
        roleId = j_data.get('roleId')
        power = j_data.get('rolePower')
        if roleId is None or len(roleId) <= 0 \
            or power is None or len(power) <= 0:
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbUserRolePower.rolePowerEdit(roleId,power)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))
            
        return jsonify(errno_no.OK.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))